import fs from 'fs';
import {mysql} from '../config/dbHelper'
import config from '../config/globalConfig';

/**
 * 创建model文件
 */
export function makeModel() {
    let resultObj = {code: 1, msg: '操作成功'};//结果对象数据
    let data = [];//文件创建信息
    const modelPath = __dirname.replace('needs', 'models');
    Object.keys(config.databaseGrouping).forEach(keyName => {
        let tempPath = modelPath + "/" + keyName + "/";
        if (!fs.existsSync(tempPath)) {
            fs.mkdir(tempPath, function (err) {
                if (err) {
                    throw err;
                }
            });
        }
    });
    mysql.select('TABLE_NAME').from('INFORMATION_SCHEMA.TABLES').where('TABLE_SCHEMA', config.database.database).then(result => {
        result.forEach((item) => {
            let tableName = item['TABLE_NAME'];
            tableName = tableName.substring(0, 1).toLowerCase() + tableName.substring(1);
            const modelsTxt = "import bookshelf from '../../config/bookshelf'\n" +
                "\n" +
                "const " + tableName + " = bookshelf.Model.extend({\n" +
                "    tableName: '" + item['TABLE_NAME'] + "',\n" +
                "    hasTimestamps: false\n" +
                "});\n" +
                "\n" +
                "export {" + tableName + "}\n";
            let dirName = "";
            Object.keys(config.databaseGrouping).forEach(keyName => {
                config.databaseGrouping[keyName].forEach(name => {
                    if (name.toLowerCase() === tableName.toLowerCase()) {
                        dirName = keyName;
                    }
                })
            });
            if (config.noLongerCreate.indexOf(item['TABLE_NAME']) < 0) {//为了避免重新创建发生覆盖操作，排除已创建
                let filePath = modelPath + "/" + dirName + "/" + tableName + ".js";
                fs.writeFile(filePath, modelsTxt, {flag: "w"}, (err) => {
                    if (err) {
                        data.push({
                            fileName: tableName,
                            result: 'error',
                            msg: err
                        })
                    } else {
                        data.push({
                            fileName: tableName,
                            result: 'success',
                            msg: 'write success'
                        })
                    }
                });
            }
        });
        resultObj.data = data;
    }).catch((err) => {
        resultObj = {code: 0, msg: '操作失败'};
    });
    return resultObj;
}


/**
 * 创建controller文件
 * @returns {{msg: string, code: number,data:array}}
 */
export function makeController() {
    let resultObj = {code: 1, msg: '操作成功'};//结果对象数据
    const controllerPath = __dirname.replace('needs', 'controllers');
    let modelsTxt = "";//文本内容
    fs.readFile(controllerPath + "/base.js", function (err, data) {
        if (err) {
            return {code: 0, msg: err};//结果对象数据
        } else {
            modelsTxt = data.toString();
        }
    });
    Object.keys(config.databaseGrouping).forEach(keyName => {
        let tempPath = controllerPath + "/" + keyName + "/";
        if (!fs.existsSync(tempPath)) {
            fs.mkdir(tempPath, function (err) {
                if (err) {
                    throw err;
                }
            });
        }
    });

    let data = [];//文件创建信息
    mysql.select('TABLE_NAME').from('INFORMATION_SCHEMA.TABLES').where('TABLE_SCHEMA', config.database.database).then(result => {
        result.forEach((item) => {
            let tableName = item['TABLE_NAME'];
            tableName = tableName.substring(0, 1).toLowerCase() + tableName.substring(1);
            let dirName = "";//文件目录
            Object.keys(config.databaseGrouping).forEach(keyName => {
                config.databaseGrouping[keyName].forEach(name => {
                    if (name.toLowerCase() === tableName.toLowerCase()) {
                        dirName = keyName;
                    }
                })
            });
            if (config.noLongerCreate.indexOf(item['TABLE_NAME']) < 0) {//为了避免重新创建发生覆盖操作，排除已创建
                let filePath = controllerPath + "/" + dirName + "/" + tableName + ".js";
                fs.writeFile(filePath, modelsTxt, {flag: "w"}, (err) => {
                    if (err) {
                        data.push({
                            fileName: tableName,
                            result: 'error',
                            msg: err
                        })
                    } else {
                        data.push({
                            fileName: tableName,
                            result: 'success',
                            msg: 'write success'
                        })
                    }
                });
            }
        });
        resultObj = {code: 1, msg: '操作成功', data: data};
    }).catch((err) => {
        resultObj = {code: 0, msg: '操作失败'};
    });
    return resultObj;
}

